package cn.mntool.backup.thread;

import cn.mntool.backup.config.BackupConfig;
import cn.mntool.backup.entity.BackupTimeProperties;
import cn.mntool.backup.server.DbBackupServer;
import cn.mntool.backup.server.DbBackupServerFactory;
import cn.mntool.backup.server.MysqlBackupServer;
import cn.mntool.backup.utils.LastTimeUtils;
import cn.mntool.backup.utils.PropertiesUtils;
import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * describe:
 *
 * @author lianying
 * @date 2019/01/31
 */
public class BackupThread extends Thread {
    /**
     * log4j
     */
    private final Logger logger= Logger.getLogger(BackupThread.class);
    private DbBackupServer dbBackupServer;
    private Long lastBackupTime=0L;
    @Override
    public void run() {
        BackupConfig backupConfig= PropertiesUtils.getBackupConfig();
        BackupTimeProperties backupTimeProperties=PropertiesUtils.getBackupTimeProperties();
        lastBackupTime=Long.valueOf(LastTimeUtils.get("lastTime"));
        switch (PropertiesUtils.get("dbType"))
        {
            case "mysql":
                default:
            dbBackupServer= DbBackupServerFactory.createServer("mysql",backupConfig);
            break;
        }

        while (true)
        {
            try {
                sleep(1000);
                //如果最后备份的时间加上周期小于当前时间，说明达到了周期的条件
                if((lastBackupTime+(backupTimeProperties.getCycle()*1000))<System.currentTimeMillis())
                {
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH");
                    String nowTime=simpleDateFormat.format(new Date());
                    Integer now=Integer.valueOf(nowTime);
                    //如果当前时间在允许备份的时间范围内，则进行备份
                    if(now>=backupTimeProperties.getBegin()&&now<=backupTimeProperties.getEnd())
                    {
                        Long startTime=System.currentTimeMillis();
                        logger.info("即将开始备份。。。");
                        //设置最后备份时间为当前时间
                        lastBackupTime=System.currentTimeMillis();
                        LastTimeUtils.update("lastTime",String.valueOf(lastBackupTime));
                        dbBackupServer.start();
                        Long time=System.currentTimeMillis()-startTime;
                        logger.info("本次备份用了"+time/1000+"秒");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
